
import numpy
from common.utils import *
from get_config import *
from midea_common.heifei.load_cgxh_cfg import *

from PIL import Image,ImageDraw,ImageFont
def cv2ImgAddText(img,text,left,top,textcolor=(0,0,255),textsize=2):
    if isinstance(img,numpy.ndarray):
        img=Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
    draw=ImageDraw.Draw(img)
    fontstyle=ImageFont.truetype("font/simsun.ttc",textsize,encoding='utf-8')
    draw.text((left,top),text,textcolor,font=fontstyle)
    return cv2.cvtColor(numpy.asarray(img),cv2.COLOR_RGB2BGR)


#bianji
def editDistDP11(s1, s2):
   m, n = len(s1), len(s2)
   dp = [[0 for _ in range(n+1)] for _ in range(m+1)]

   for i in range(m + 1):
       for j in range(n + 1):
           if i == 0:
               dp[i][j] = j

           elif j == 0:
               dp[i][j] = i

           elif s1[i-1] == s2[j-1]:
               dp[i][j] = dp[i-1][j-1]

           else:
               dp[i][j] = 1 + min(dp[i][j-1],  # Insert
                                  dp[i-1][j],  # Remove
                                  dp[i-1][j-1])  # Replace

   return dp[m][n]

char_skep_map = {
}

char_number = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-/' # ⅠⅢⅡ
skip_chars = '0oO 1lI 2Z'.split()

def filter_string5(s, chars):
    aa = ''.join([c for c in s if c in chars])
    aa = aa.replace('W', 'VV')
    for skip_char in skip_chars:
        for x in skip_char:
            aa = aa.replace(x, skip_char[0])
    return aa

def test_filter_string5():
    s = '999a1b2c3d4e5f6g7h8i9j0'
    print(filter_string5(s, 'a0123456789'))
    return 0

#test_filter_string5()

def editDistDP(s1, s2):
    s1 = filter_string5(s1,char_number)
    s2 = filter_string5(s2,char_number)
    m, n = len(s1), len(s2)
    dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
 
    for i in range(m + 1):
        for j in range(n + 1):
            if i == 0:
                dp[i][j] = j
 
            elif j == 0:
                dp[i][j] = i
 
            elif s1[i-1] == s2[j-1]:
                dp[i][j] = dp[i-1][j-1]
 
            else:
                a = 10
                dp[i][j] = a + min(dp[i][j-1],  # Insert
                                   dp[i-1][j],  # Remove
                                  dp[i-1][j-1])  # Replace
               
    dd = dp[m][n]
    return dd



#print(editDistDP('KFR-72T2/B3DN1-LX(1)111', 'KER-72T2/B3DN1-LX（1）llI'))

#编辑距离
def edit_dist(t1, t2):
    l = max(len(t1), len(t2))
    if 0==l:
        return 0
    return editDistDP11(t1, t2)/l

def get_biaoqian11():
    #"MJV-36T2X-TS":96517, "MJV-28T2X-TS":96521,"MJV-28T2/X-TS":96521,"MJV-28T2/-TS": 96521,"MJV-36T2/X-TS":96517,"MJV-36T2/D-TS":96517,"MJV-36T2/-TS":96517,
    biaoqianfn = "E:/code/biaoqian.json"
    result = {}
    if not os.path.exists(biaoqianfn):
        biaoqianfn = 'D:/biaoqian.json'
    try:
        with open(biaoqianfn,'r',encoding= 'utf-8') as f:
            str1 = f.read()
            result = json.loads(str1)
    except Exception as e:
        logger.info(f'biaoqianfn {biaoqianfn} {str(e)}')
        pass

    biaoqian = {}
    for x in result:
        biaoqian[result[x]] = x
    # key_list = list(jixingma.keys())
    # value_list = list(jixingma.values())
    return biaoqian

if 0:
    aa = get_biaoqian()
    dd = []
    for x in aa:
        bb = {x:{'ocr':[aa[x]]}}
        dd.append(json.dumps(bb))
    open(r'D:\code\git\ywlydd\nei1_mingpai\peifang_write.txt', 'w').write('\n'.join(dd))


def get_xinhao(product):
    biaoqian = get_biaoqian()
    ppp = product[6:11]
    if ppp in biaoqian:
        get_penma = biaoqian[ppp]
        return get_penma

    return None

def judge_product11(out,product):
    quexian = []
    if product =='NOREAD':
        quexian.append('NOREAD')
        return quexian
    
    get_penma = get_xinhao(product)
    if get_penma is None:
        quexian.append('没条码对应设置')
        return quexian
    #out = []
    if len(out) == 0:  # 未检测到字符则直接返回结果
        quexian.append('没检测到文字')
        return quexian

    end1 = 1
    try:
        score = 100
        edist = config['edist']
        for i in range(len(out)):
            # if out[i][1] != '' and len(out[i][1]) >6:
            # 首先判断其key值是否在字典所有的key值中
            key1 = out[i][1]
            if len(key1)<3:
                continue
            
            # get_penma = list(jixingma.keys())[list(jixingma.values()).index(str(ppp))]
            # get_penma = list(result.keys())[list(result.values()).index(str(ppp))]
            # print(f'get_penma:{get_penma}')
            logger.info(f'judge_product: get_penma:{get_penma} key1:{key1}')
            #计算两个字符串的编辑距离
            x = editDistDP(key1, get_penma)
            logger.info(f'x:{x} edist:{edist}')
            # print(f'*******************x:{x}')
            if x < edist:
                end1 = 0
            else:
                if len(out[i])>2:
                    aa = [x[2] for x in out[i][2]]
                    if len(aa)>0:
                        ss = min(aa)
                        score = min(score, ss)
                        
    except Exception as e:
        logger.info(f'judge_product: 逻辑:{str(e)}')
        end1 = 1
    if end1>0:
        quexian.append('不匹配')
    return quexian

def judge_product(out,product):
    quexian = []
    if product =='NOREAD':
        #quexian.append('NOREAD')
        return quexian,out

    pa,fn = os.path.split(biaoqianfn)
    biaoqianfn1 = find_file(fn, ['./', pa, get_model_pa()])
    cgxh = load_cgxh_cfg(biaoqianfn1)

    if len(product)>15:
        jixing = product[6:11]
    elif len(product)==5:
        jixing = product
        
    if jixing not in cgxh:
        quexian.append('没条码对应设置')
        return quexian,out
    
    get_penma = cgxh[jixing]['ocr'][0]
    #out = []
    if len(out) == 0:  # 未检测到字符则直接返回结果
        quexian.append('没检测到文字')
        return quexian,out

    end1 = 1
    try:
        score = 100
        edist = config['edist']
        if len(out)>0:
            ii = None
            xx = 100000
            for i in range(len(out)):
                # if out[i][1] != '' and len(out[i][1]) >6:
                # 首先判断其key值是否在字典所有的key值中
                key1 = out[i][1]
                if len(key1)<3:
                    continue
                
                # get_penma = list(jixingma.keys())[list(jixingma.values()).index(str(ppp))]
                # get_penma = list(result.keys())[list(result.values()).index(str(ppp))]
                # print(f'get_penma:{get_penma}')
                logger.info(f'judge_product: get_penma:{get_penma} key1:{key1}')
                #计算两个字符串的编辑距离
                x = editDistDP(key1, get_penma)
                logger.info(f'x:{x} edist:{edist}')
                # print(f'*******************x:{x}')
                if x < xx:
                    xx = x
                    ii = i
                else:
                    if len(out[i])>2:
                        aa = [x[2] for x in out[i][2]]
                        if len(aa)>0:
                            ss = min(aa)
                            score = min(score, ss)
            
            if ii is not None:
                if xx<edist:
                    pts, l, score = out[ii][:3]
                    out = [[pts, get_penma, score]]
                    if xx < edist:
                        end1 = 0
    except Exception as e:
        logger.info(f'judge_product: 逻辑:{str(e)}')
        end1 = 1
    if end1>0:
        quexian.append('铭牌不匹配')
    return quexian, out


def find_min_eddist(s, xx):
    sout = s
    mind = 10000
    if len(xx)>0:
        dd = [editDistDP(s, x) for x in xx]
        minid = np.argmin(dd)
        sout = xx[minid]
        mind = dd[minid]
    return sout, mind
